<script>
import { getDepartment, delDepartment } from '@/api/department'
import { transListToTreeData } from '@/utils'
import AddDepts from '@/views/department/components/add-depts'

export default {
  name: 'Department',
  components: { AddDepts },
  data() {
    return {
      dialogVisible: false,
      parentId: null,
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.departmentList()
  },
  methods: {
    async departmentList() {
      const result = await getDepartment()
      this.depts = transListToTreeData(result, 0)
    },
    async operateDepartment(type, parentId) {
      if (type === 'del') {
        this.$confirm('您确定要删除吗').then(async() => {
          await delDepartment(parentId)
          this.$message.success('删除成功')
          this.departmentList()
        })
        return
      }
      this.parentId = parentId
      this.dialogVisible = true
      if (type === 'edit') {
        // this.$nextTick允许你在下一次 DOM 更新循环结束后执行回调，从而访问最新的 DOM 结构
        this.$nextTick(() => {
          this.$refs.updateDept.getDepartmentDetail()
        })
      }
    }
  }
}
</script>

<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :expand-on-click-node="false" :data="depts" :props="defaultProps">
        <!--        作用域插槽-->
        <template v-slot:default="{ data }">
          <el-row style="width: 100%" type="flex" justify="space-between" align="middle">
            <el-col>{{ data.name }}</el-col>
            <el-col :span="4">
              <span class="tree-manager">{{ data.managerName }}</span>
              <el-dropdown @command="operateDepartment($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down el-icon--right" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <AddDepts ref="updateDept" :show-dialog.sync="dialogVisible" :pid="parentId" @flush="departmentList" />
  </div>
</template>

<style scoped>

.container {
  padding: 20px;
}
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
.tree-manager {
  display: inline-block;
  width: 80px;
  margin: 10px;
}
</style>
